package com.datamation.swadeshi.view;

import java.util.ArrayList;

import com.datamation.swadeshi.R;
import com.datamation.swadeshi.adapter.InvoiceHistoryAdapter;
import com.datamation.swadeshi.adapter.LoadingHistoryAdapter;
import com.datamation.swadeshi.adapter.SetTitleAdapter;
import com.datamation.swadeshi.control.LoadingPrintPreviewAlertBox;
import com.datamation.swadeshi.control.ReferenceNum;
import com.datamation.swadeshi.control.SalesPrintPreviewAlertBox;
import com.datamation.swadeshi.control.data.FTranDetDS;
import com.datamation.swadeshi.control.data.FTranHedDS;
import com.datamation.swadeshi.control.data.OrdDetDS;
import com.datamation.swadeshi.control.data.OrdHedDS;
import com.datamation.swadeshi.model.FTranHed;
import com.datamation.swadeshi.model.OrdHed;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.SearchView.OnQueryTextListener;

public class FragmentInventoryControlUnLoading extends Fragment
{
	View view;
	private ActionBar actionBar;
	ListView lvLoadingList;
	ArrayList<FTranHed> arrayList;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.inventory_control_unloadingmain, container, false);
		setHasOptionsMenu(true);
		lvLoadingList = (ListView) view.findViewById(R.id.lvPhoneLoadinglist);
		registerForContextMenu(lvLoadingList);
		
		SetTitleAdapter adapterUnload =new SetTitleAdapter();
		adapterUnload.createCutomActionBarTitle("UnLoading", getActivity());

		getActivity().getActionBar().removeAllTabs();
		getActivity().getActionBar().setNavigationMode(0);
		
		displayInvoiceHistory();
		
		

        view.setFocusableInTouchMode(true);
        view.requestFocus();
        view.setOnKeyListener(new View.OnKeyListener() {
		        @Override
		        public boolean onKey(View v, int keyCode, KeyEvent event) {
		            Log.i("", "keyCode: " + keyCode);
		            if( keyCode == KeyEvent.KEYCODE_BACK ) {
		            	Toast.makeText(getActivity(),"Back Navigationid is disable", Toast.LENGTH_SHORT).show();
		               // getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
		                return true;
		            }else if ((keyCode == KeyEvent.KEYCODE_HOME)) {
		    			
		    			getActivity().finish();
		    			
		    			return true;

		    		} else {
		                return false;
		            }
		        }
		    });
        
        
		return view;
	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		
		for(int i = 0; i < menu.size(); ++i){
			menu.removeItem(menu.getItem(i).getItemId());
		}
		
		inflater.inflate(R.menu.frag_stockloading_phone_menu, menu);
		SearchView searchView = (SearchView) menu.findItem(R.id.action_customer_search_phone).getActionView();
		searchView.setOnQueryTextListener(new OnQueryTextListener() {
			
			@Override
			public boolean onQueryTextSubmit(String query) {
				return false;
			}
			
			@Override
			public boolean onQueryTextChange(String newText) {

				return false;
			}
		});
		
	
		super.onCreateOptionsMenu(menu, inflater);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.action_stockloading_phone_new)
		{
			FragmentTransaction transaction = getFragmentManager().beginTransaction();
			transaction.replace(R.id.frame_container, new FragmentInventoryControlUnLoadingMain());
			transaction.addToBackStack(null);
			transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			transaction.commit();
		}
		if(item.getItemId() == R.id.action_pre_sales_save)
		{
			item.setCheckable(false);
			
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
	      super.onCreateContextMenu(menu, v, menuInfo);
	      if (v.getId()==R.id.lvPhoneLoadinglist) {
	          MenuInflater inflater = getActivity().getMenuInflater();
	          inflater.inflate(R.menu.menu_list, menu);
	      }
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	     AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	     FTranHed trnHed = arrayList.get(info.position);
	      switch(item.getItemId()) {
	         case R.id.cancel:
	        	// TODO Auto-generated method stub
					
					delete(getActivity(), trnHed.getFTRANHED_REFNO());
	            return true;
	          case R.id.print:
	            // print stuff here
	        	  setBluetooth(true);
	        	ReferenceNum referenceNum =new  ReferenceNum(getActivity());
	        	LoadingPrintPreviewAlertBox alertBox=new LoadingPrintPreviewAlertBox(getActivity());
				alertBox.PrintDetailsDialogbox(getActivity(), "",trnHed.getFTRANHED_REFNO());
					
	        	  
	          return true;
	            default:
	                return super.onContextItemSelected(item);
	      }
	}
	
	
	
	
	private void displayInvoiceHistory() {
		// TODO Auto-generated method stub
		lvLoadingList = (ListView) view.findViewById(R.id.lvPhoneLoadinglist);
		lvLoadingList.clearTextFilter();
		FTranHedDS hedDS = new FTranHedDS(getActivity());
		arrayList = hedDS.getAllHedUnLoadData();
		lvLoadingList.setAdapter(new LoadingHistoryAdapter(getActivity(), arrayList));
	}
	
	private void delete(final Context context,final String refno){

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
		//alertDialogBuilder.setTitle(title);
		alertDialogBuilder.setMessage("Are you sure you want to cancel this entry?");
		
		final FTranHedDS trnHedDS =new FTranHedDS(getActivity());
		final FTranDetDS detDS=new FTranDetDS(getActivity());
		
		alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
		alertDialogBuilder.setCancelable(false)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								
								//delete data
								try {
									trnHedDS.restData(refno); //FORDHED DATA
									//FTranHedDS.
								}catch(Exception e){
									Log.w("Cancel FORDHED Data Erorrrr ", e.toString());
								}
								try {
									detDS.restData(refno); // FORDDET DATA
								}catch(Exception e){
									Log.w("Cancel FORDDET Data Erorrrr ", e.toString());
								}finally{
									displayInvoiceHistory();
								}

							}
					})
				.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,	int id) {
								dialog.cancel();
							}
						});
		
		AlertDialog alertD = alertDialogBuilder.create();

		alertD.show();
	}
	
	public static boolean setBluetooth(boolean enable) {
	    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	    boolean isEnabled = bluetoothAdapter.isEnabled();
	    if (enable && !isEnabled) {
	        return bluetoothAdapter.enable(); 
	    }
	    else if(!enable && isEnabled) {
	        return bluetoothAdapter.disable();
	    }
	    // No need to change bluetooth state
	    return true;
	}
	
}
